﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Chummer
{
    public partial class frmInitiativeTracker : Form
    {
        #region Properties

        private List<CharacterInit> characters;
        private Random objRandom;
        private int index;
        private int round;
        private int pass;
        private bool finishedCombatTurn;
        private int totalChummersWithNoInit;


        #endregion



        public frmInitiativeTracker()
        {
            InitializeComponent();
            this.CenterToParent();
            characters = new List<CharacterInit>();
            objRandom = new Random();
            characters.Add(new CharacterInit()
            {
                Name="Sheppard",
                InitStart=12,
                IsNPC=false,
                NbDice=4
            });

            round = 1;
            toolStripStatusLabel_Round.Text = "Round " + round;
            pass = 1;
            toolStripStatusLabel_Pass.Text = "Pass " + pass;
            finishedCombatTurn = false;

            // setup the list of chummers to show 
            BindListView();
        }



        private void BindListView()
        {
            listView_Fighter.Items.Clear();

            if (characters.Count > 0)
            {
                ListViewItem item;
                foreach (CharacterInit c in characters)
                {
                    item = new ListViewItem(c.Name);
                    if (c.IsNPC)
                    {
                        item.Text += " (NPC)";
                    }

                    item.SubItems.Add(c.NbDice + "D + " + c.InitStart);
                    item.SubItems.Add(c.InitValue.ToString());
                    item.SubItems.Add(c.IsUsingFullDefence.ToString());
                    listView_Fighter.Items.Add(item);
                }
            }
        }






        #region Events
        private void cmdAddCharacter_Click(object sender, EventArgs e)
        {
            if (ValidateCharacterAdd())
            {
                characters.Add(new CharacterInit()
                {
                    Name = textBox_Name.Text,
                    IsNPC = checkBox_NPC.Checked,
                    NbDice = int.Parse(textBox_NbDice.Text),
                    InitStart = int.Parse(textBox_InitStat.Text),
                    InitValue = RollInitiative(int.Parse(textBox_NbDice.Text), int.Parse(textBox_InitStat.Text)),
                    IsUsingFullDefence = false
                });
                characters = characters.OrderByDescending(o => o.InitValue).ToList<CharacterInit>();
                BindListView();
            }
        }

        /*
         * Removes the chosen chummer from the list
         */
        private void cmdRemoveCharacter_Click(object sender, EventArgs e)
        {
            // check if we have selected a chummer in the list
            if (this.listView_Fighter.SelectedItems.Count == 0)
                MessageBox.Show("Please Select a Chummer to remove");
            else
            {
                foreach(ListViewItem li in listView_Fighter.SelectedItems)
                {
                    characters.RemoveAt(li.Index);
                    listView_Fighter.Items.RemoveAt(li.Index);
                }
                if (this.listView_Fighter.Items.Count > 0)
                    this.listView_Fighter.Items[0].Selected = true; // reset the selected item to the first item in the list
            }
        }

        /*
         * Subtracts 1 init
         */
        private void btnMinusInit1_Click(object sender, EventArgs e)
        {
            // check if we have selected a chummer in the list
            if (listView_Fighter.SelectedItems.Count == 0)
                MessageBox.Show("Please Select a Chummer to remove");
            else
            {
                ApplyInitChange(-1);
            }
        }

        /*
         * Add 1 init
         */
        private void btnAdd1Init_Click(object sender, EventArgs e)
        {
            // check if we have selected a chummer in the list
            if (listView_Fighter.SelectedItems.Count == 0)
                MessageBox.Show("Please Select a Chummer to remove");
            else
            {
                ApplyInitChange(1);
            }
        }

        /*
         * Subtracts 5 init
         */
        private void btnMinus5Init_Click(object sender, EventArgs e)
        {
            // check if we have selected a chummer in the list
            if (listView_Fighter.SelectedItems.Count == 0)
                MessageBox.Show("Please Select a Chummer to remove");
            else
            {
                ApplyInitChange(-5);
            }
        }

        /*
         * Add 5 init
         */
        private void btnAdd5Init_Click(object sender, EventArgs e)
        {
            // check if we have selected a chummer in the list
            if (listView_Fighter.SelectedItems.Count == 0)
                MessageBox.Show("Please Select a Chummer to remove");
            else
            {
                ApplyInitChange(5);
            }
        }

        /*
         * Subtracts 10 init
         */
        private void btnMinus10Init_Click(object sender, EventArgs e)
        {
            // check if we have selected a chummer in the list
            if (listView_Fighter.SelectedItems.Count == 0)
                MessageBox.Show("Please Select a Chummer to remove");
            else
            {
                ApplyInitChange(-10);
            }
        }

        /*
         * Add 10 init
         */
        private void btnAdd10Init_Click(object sender, EventArgs e)
        {
            // check if we have selected a chummer in the list
            if (listView_Fighter.SelectedItems.Count == 0)
                MessageBox.Show("Please Select a Chummer to remove");
            else
            {
                ApplyInitChange(10);
            }
        }

        private void toolStripStatusLabel_NewCombat_Click(object sender, EventArgs e)
        {
            // for every checked character, we re-roll init
            if (characters.Count > 0)
            {
                foreach (CharacterInit c in characters)
                {
                    c.InitValue = RollInitiative(c.NbDice, c.InitStart);
                    c.IsUsingFullDefence = false;
                }
                characters = characters.OrderByDescending(o => o.InitValue).ToList<CharacterInit>();
            }

            BindListView();
            finishedCombatTurn = false;
            index = 0;
            round = 1;
            pass = 1;
            toolStripStatusLabel_Round.Text = "Round " + round;
            toolStripStatusLabel_Pass.Text = "Pass " + pass;
            totalChummersWithNoInit = 0;
        }


        /*
        * goes to the next chummer in the list
        */

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (this.finishedCombatTurn)
            {
                // for every checked character, we re-roll init
                if (characters.Count > 0)
                {
                    foreach (CharacterInit c in characters)
                    {
                        c.InitValue = RollInitiative(c.NbDice, c.InitStart);
                        c.IsUsingFullDefence = false;
                    }
                    characters = characters.OrderByDescending(o => o.InitValue).ToList<CharacterInit>();
                }

                BindListView();
                finishedCombatTurn = false;
                index = 0;
                round++;
                pass = 1;
                toolStripStatusLabel_Round.Text = "Round " + round;
                toolStripStatusLabel_Pass.Text = "Pass " + pass;
                totalChummersWithNoInit = 0;
            }
            if (this.index == this.characters.Count - this.totalChummersWithNoInit)
            {
                // increment the pass count since we have reached the end of the list
                pass++;
                this.toolStripStatusLabel_Pass.Text = "Pass " + pass;

                // reset the the round with a minus ten on all
                foreach(CharacterInit c in characters)
                {
                    if (c.InitValue > 0)
                    {
                        c.InitValue = c.InitValue - 10;
                    }
                }

                this.finishedCombatTurn = (characters.Where(c => c.InitValue > 0).Count() == 0);
                BindListView();
                this.index = 0;
            }
            else
            {
                // setup the next chummer to go
                while (this.index < this.characters.Count && this.characters[this.index].InitValue <= 0)
                    this.index++;

                // check if there are no more chummer's which can move
                if (characters.Where(c => c.InitValue > 0).Count() == 0)
                {
                    this.finishedCombatTurn = true;
                    this.index = 0;
                    return; // we are finished
                }
                if (index < characters.Count())
                {
                    listView_Fighter.Select();
                    listView_Fighter.SelectedIndices.Clear();
                    listView_Fighter.SelectedIndices.Add(index);
                    this.index++;
                }
            }
        }

        #endregion




        #region Methods

        private bool ValidateCharacterAdd()
        {
            bool bValid = true;

            string lstErreur = "";
            if (String.IsNullOrWhiteSpace(textBox_Name.Text))
            {
                bValid = false;
                lstErreur += "-Specify a name\n\r";
            }

            int temp;
            if (int.TryParse(textBox_NbDice.Text.Trim(), out temp))
            {
                if (temp < 0)
                {
                    bValid = false;
                    lstErreur += "-The number of dice must be a positive number.\n\r";
                }
            }
            else
            {
                bValid = false;
                lstErreur += "-The number of dice must be a number.\n\r";
            }

            if (!int.TryParse(textBox_InitStat.Text.Trim(), out temp))
            {
                bValid = false;
                lstErreur += "-The initiative bonus must be a number.\n\r";
            }

            if (!bValid)
            {
                MessageBox.Show("Please correct these errors before clicking Add: \r\n" + lstErreur);
            }

            return bValid;
        }

        private int RollInitiative(int nbDice, int bonus)
        {
            int initValue = bonus;

            for (int i = 0; i < nbDice; i++)
            {
                initValue += objRandom.Next(1, 7);
            }

            return initValue;
        }

        /*
         * Applies the specified amount of initiative to the 
         * currently selected player
         */
        private void ApplyInitChange(int value)
        {
            if (this.listView_Fighter.SelectedItems.Count >= 0)
            {
                ListView.SelectedIndexCollection idxCol = listView_Fighter.SelectedIndices;
                foreach (int i in idxCol)
                {
                    // pull the simple character out
                    characters[i].InitValue += value;

                    // if negative or 0 init add to the count
                    if (characters[i].InitValue < 1)
                        this.totalChummersWithNoInit++;
                }
 
                BindListView();
                foreach (int i in idxCol)
                {
                    listView_Fighter.Items[i].Selected = true;
                }
            }
        }

        #endregion


        #region Helper class
        class CharacterInit
        {

            public string Name { get; set; }
            public int NbDice { get; set; }
            public int InitStart { get; set; }
            public bool IsNPC { get; set; }
            
            //These properties changes each combat turn
            public int InitValue { get; set; }
            public bool IsUsingFullDefence { get; set; }


        }
        #endregion














    }











}
